package chapter13;

import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;

public class ExecuteSQL {

    private String driver;
    private String url;
    private String user;
    private String pass;

    public void initParam(String paramFile) throws Exception {
        Properties props = new Properties();
        props.load(new FileInputStream(paramFile));
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        user = props.getProperty("username");
        pass = props.getProperty("password");
    }

    public void executeSql(String sql) throws Exception {
        Class.forName(driver);
        try(Connection connection = DriverManager.getConnection(url, user, pass);
            Statement statement = connection.createStatement())
        {
            boolean hasResult = statement.execute(sql);
            if(hasResult) {
                try(ResultSet rs = statement.getResultSet()){
                    ResultSetMetaData data = rs.getMetaData();
                    int columnCount = data.getColumnCount();
                    while(rs.next()) {
                        for (int i = 0; i < columnCount; i++) {
                            System.out.print(rs.getString(i + 1) + "\t");
                        }
                        System.out.println("\n");
                    }
                }
            } else {
                System.out.println("该SQL影响的记录有:" + statement.getUpdateCount() + "条");
            }
        }
    }

    public static void main(String[] args) throws Exception {
        ExecuteSQL es = new ExecuteSQL();
        es.initParam("src/main/resources/db.properties");
        String dropSql = "drop table if exists jdbc_test";
        es.executeSql(dropSql);
        String createSql = "create table jdbc_test"
                + "(jdbc_id int auto_increment primary key, "
                + "test_name varchar(255))";
        es.executeSql(createSql);
        String insertSql = "insert into jdbc_test(test_name)"
                + "select student_name from t_student";
        es.executeSql(insertSql);
        String querySql = "select * from jdbc_test";
        es.executeSql(querySql);
    }
}
